'use strict'

var https = require('https');
var fs = require('fs');


var express = require('express');
var serveIndex = require('serve-index');

var socketIO = require('socket.io');

var options = {
    key: fs.readFileSync('./7069231_www.coot.online.key'),
    cert: fs.readFileSync('./7069231_www.coot.online.pem')
}

var app = express();
app.use(serveIndex('./public'))
app.use(express.static('./public'))

var USERCOUNT = 3;

//创建https服务
var https_server = https.createServer(options, app);
//socketio创建
var io = socketIO.listen(https_server);

//监听客户端连接
io.on('connection', (socket) => {
    //监听join命令
    socket.on('join', (room) => {
        //将客户加入一个房间
        socket.join(room);
        //获得房间的对象
        var myRoom = io.sockets.adapter.rooms[room];
        //获得房间的所有连接数量
        var users = Object.keys(myRoom.sockets).length;

        console.info('用户数量' + users);

        if (users < USERCOUNT) {
            //回复当前连接
            socket.emit('joined', room, socket.id);
            //回复给其他人回复
            socket.to(room).emit('otherjoin', room, socket.id);
        }
        else {
            //新加入人踢出
            socket.leave(room);
            socket.emit('full', room);
        }

        //回复除自己外的房间所有人
        // socket.to(room).emit('joined', room, socket.id);
        //回复房间所有人
        // socket.in(room).emit('joined', room, socket.id);
        //所有人发送
        // socket.broadcast.emit('joined', room, socket.id);
    });
    //监听leave命令
    socket.on('leave', (room) => {

        //获得房间的对象
        var myRoom = io.sockets.adapter.rooms[room];
        //获得房间的所有连接数量
        var users = Object.keys(myRoom.sockets).length;
        //将客户加入一个房间
        socket.leave(room);

        console.info('用户数量1' + users - 1);

        socket.emit('leaved', room, socket.id);
        socket.to(room).emit('bye', room, socket.id);
    });
    //监听leave命令
    socket.on('message', (room, data) => {

        console.info('room' + room);
        console.info('socket' + socket.id);
        console.info('data' + data);
        
        //回复房间所有人
        socket.to(room).emit('message', room, socket.id, data);
    });
});

https_server.listen(443, '0.0.0.0');


